<?php

/* 生成纯html */

define('IN_ECS', true);

$act = !empty($_REQUEST['act']) ? $_REQUEST['act'] : 'index';
if($act == 'goods') $goods_id = isset($_REQUEST['id'])  ? intval($_REQUEST['id']) : 0;

require(dirname(__FILE__) . '/includes/init.php');

if($act == 'goods'){
	require(dirname(__FILE__) . '/includes/lib_comment.php');

	$affiliate = unserialize($GLOBALS['_CFG']['affiliate']);
	$smarty->assign('affiliate', $affiliate);

	$smarty->assign('w_id', $w_id);
	$smarty->assign('store_list', get_storelist(explode("-",$_COOKIE['rg_ipLoc'])));
}
$smarty->assign('act',      $act); 

$display = $_CFG['show_order_type'] == '0' ? 'list' : ($_CFG['show_order_type'] == '1' ? 'grid' : 'text');
$order = $_CFG['sort_order_method'] == '0' ? 'DESC' : 'ASC';
$size = isset($_CFG['page_size'])  && intval($_CFG['page_size']) > 0 ? intval($_CFG['page_size']) : 10;

$rewrite = intval($GLOBALS['_CFG']['rewrite']);

/*首页*/
if ($act == 'index'){
	assign_template();
	$position = assign_ur_here();
	$smarty->assign('page_title',      $position['title']); 

	$smarty->assign('keywords',        htmlspecialchars($_CFG['shop_keywords']));
	$smarty->assign('description',     htmlspecialchars($_CFG['shop_desc']));
	$smarty->assign('categories',      get_categories_tree());
	$smarty->assign('helps',           get_shop_help());

	$links = index_get_links();
	$smarty->assign('img_links',       $links['img']);
	$smarty->assign('txt_links',       $links['txt']);
	
	$smarty->assign("flash",get_flash_xml());
	$smarty->assign('flash_count',count(get_flash_xml()));

	assign_dynamic('index');

	$cache_id = sprintf('%X', crc32($_SESSION['user_rank'] . '-' . $_CFG['lang']));
	$rg_html = CreateHtml("index.dwt", "index.html", $cache_id);
	if($rg_html){
		$message = '操作成功！';
		ecs_header("Location: ".ADMIN_PATH."/rg_html.php?act=re_html&message=".$message); exit;
	}else{
		$message = '操作失败！';
		ecs_header("Location: ".ADMIN_PATH."/rg_html.php?act=re_html&message=".$message); exit;
	}
}
/*分类商品列表*/
elseif ($act == 'category'){
	if($_REQUEST['is_json']){
		include_once('includes/cls_json.php');
		$json = new JSON;
		$result   = array('error' => 0, 'content' => '', 'id' => 0);

		$uri_ext = $rewrite ? '-b0' : '';
		$sort   = $_CFG['sort_order_type'] == '0' ? 'salenum' : ($_CFG['sort_order_type'] == '1' ? 'shop_price' : 'last_update');

		$cat_id = $_REQUEST['id'] ? $_REQUEST['id'] : '0';

		if($cat_id){
			$new_cat_id = $db->getOne("SELECT cat_id FROM " . $ecs->table('category') . " WHERE cat_id > '$cat_id' order by cat_id ASC");
			$result['id'] = $new_cat_id;

			$cache_id = sprintf('%X', crc32($cat_id.'-'.$display.'-'.$sort.'-'.$order.'-1-'.$size.'-'.$_SESSION['user_rank'].'-'.$_CFG['lang'].'-0-0-0-0'));
			$rg_caches = get_category_caches($cat_id, 0, 0, 0, $size, 1, $sort, $order, $display); 
			$rg_html = CreateHtml("category.dwt", "product/list_".$cat_id.$uri_ext.".html", $cache_id);
			$result['content'] = $db->getOne("SELECT cat_name FROM " . $ecs->table('category') . " WHERE cat_id = '$cat_id'");
		}else{
			$result['error'] = 1;
		}
		
		die($json->encode($result));
	}else{
		$cat_id = $db->getOne("SELECT cat_id FROM " . $ecs->table('category') . " order by cat_id ASC");
		$smarty->assign('id', $cat_id);
	}
}
/*商品详情页*/
elseif ($act == 'goods'){
	if($_REQUEST['is_json']){
		include_once('includes/cls_json.php');
		$json = new JSON;
		$result   = array('error' => 0, 'content' => '', 'id' => 0);

		if($goods_id){
			$goods_ids = explode(',', $_SESSION['goods_id_arr']);
			$rg_key = array_search($goods_id, $goods_ids)+1;
			$result['id'] = $goods_ids[$rg_key] ? $goods_ids[$rg_key] : 0;

			$w_id = get_w_id($goods_id);
			$cache_id = sprintf('%X', crc32($goods_id . '-' . $_SESSION['user_rank'].'-'.$_CFG['lang'].'-'.$w_id));
			$rg_caches = get_goods_caches($goods_id); 
			$rg_html = CreateHtml("goods.dwt", "product/".$goods_id.".html", $cache_id);
			$result['content'] = $db->getOne("SELECT goods_name FROM " . $ecs->table('goods') . " WHERE goods_id = '$goods_id'");
		}else{
			$result['error'] = 1;
		}
		
		die($json->encode($result));
	}else{
		$_SESSION['goods_id_arr'] = $goods_id_arr = !empty($_REQUEST['goods_id']) ? $_REQUEST['goods_id'] : 0;
		$goods_ids = explode(',', $goods_id_arr);
		$smarty->assign('id', $goods_ids[0]);
	}
}
/*品牌商品列表*/
elseif ($act == 'brand'){
	if($_REQUEST['is_json']){
		include_once('includes/cls_json.php');
		$json = new JSON;
		$result   = array('error' => 0, 'content' => '', 'id' => 0);

		$uri_ext = $rewrite ? '-c0' : '';
		$sort   = $_CFG['sort_order_type'] == '0' ? 'goods_id' : ($_CFG['sort_order_type'] == '1' ? 'shop_price' : 'last_update');

		$brand_id = $_REQUEST['id'] ? $_REQUEST['id'] : '0';

		if($brand_id){
			$new_brand_id = $db->getOne("SELECT brand_id FROM " . $ecs->table('brand') . " WHERE brand_id > '$brand_id' order by brand_id ASC");
			$result['id'] = $new_brand_id;

			$cache_id = sprintf('%X', crc32($brand_id . '-' . $display . '-' . $sort . '-' . $order . '-1-' . $size . '-' . $_SESSION['user_rank'] . '-' . $_CFG['lang'] . '-0'));
			$rg_caches = get_brand_caches($brand_id, 0, $size, 1, $sort, $order, $display, 0); 
			$rg_html = CreateHtml("brand.dwt", "product/brand_".$brand_id.$uri_ext.".html", $cache_id);
			$result['content'] = $db->getOne("SELECT brand_name FROM " . $ecs->table('brand') . " WHERE brand_id = '$brand_id'");
		}else{
			$result['error'] = 1;
		}
		
		die($json->encode($result));
	}else{
		$brand_id = $db->getOne("SELECT brand_id FROM " . $ecs->table('brand') . " order by brand_id ASC");
		$smarty->assign('id', $brand_id);
	}
}
/*分类文章列表*/
elseif ($act == 'article_cat'){
	if($_REQUEST['is_json']){
		include_once('includes/cls_json.php');
		$json = new JSON;
		$result   = array('error' => 0, 'content' => '', 'id' => 0);

		$cat_id = $_REQUEST['id'] ? $_REQUEST['id'] : '0';

		if($cat_id){
			$new_cat_id = $db->getOne("SELECT cat_id FROM " . $ecs->table('article_cat') . " WHERE cat_id > '$cat_id' order by cat_id ASC");
			$result['id'] = $new_cat_id;

			$cache_id = sprintf('%X', crc32($cat_id . '-1-' . $_CFG['lang']));
			$rg_caches = get_article_cat_caches($cat_id, 1); 
			$rg_html = CreateHtml("article_cat.dwt", "news/list_".$cat_id.".html", $cache_id);
			$result['content'] = $db->getOne("SELECT cat_name FROM " . $ecs->table('article_cat') . " WHERE cat_id = '$cat_id'");
		}else{
			$result['error'] = 1;
		}
		
		die($json->encode($result));
	}else{
		$cat_id = $db->getOne("SELECT cat_id FROM " . $ecs->table('article_cat') . " order by cat_id ASC");
		$smarty->assign('id', $cat_id);
	}
}
/*文章详情页*/
elseif ($act == 'article'){
	if($_REQUEST['is_json']){
		require(dirname(__FILE__) . '/includes/lib_comment.php');
		include_once('includes/cls_json.php');
		$json = new JSON;
		$result   = array('error' => 0, 'content' => '', 'id' => 0);
		
		$article_id = $_REQUEST['id'] ? $_REQUEST['id'] : '0';
		if($article_id){
			$article_ids = explode(',', $_SESSION['article_id_arr']);
			$rg_key = array_search($article_id, $article_ids)+1;
			$result['id'] = $article_ids[$rg_key] ? $article_ids[$rg_key] : 0;

			$cache_id = sprintf('%X', crc32($article_id . '-' . $_CFG['lang']));
			$rg_caches = get_article_caches($article_id); 
			$rg_html = CreateHtml("article.dwt", "news/".$article_id.".html", $cache_id);
			$result['content'] = $db->getOne("SELECT title FROM " . $ecs->table('article') . " WHERE article_id = '$article_id'");
		}else{
			$result['error'] = 1;
		}
		
		die($json->encode($result));
	}else{
		$_SESSION['article_id_arr'] = $article_id_arr = !empty($_REQUEST['article_id']) ? $_REQUEST['article_id'] : 0;
		$article_ids = explode(',', $article_id_arr);
		$smarty->assign('id', $article_ids[0]);
	}
}
/*帮助详情页*/
elseif ($act == 'help'){
	if($_REQUEST['is_json']){
		require(dirname(__FILE__) . '/includes/lib_comment.php');
		include_once('includes/cls_json.php');
		$json = new JSON;
		$result   = array('error' => 0, 'content' => '', 'id' => 0);

		$article_id = $_REQUEST['id'] ? $_REQUEST['id'] : '0';
		if($article_id){
			$article_ids = explode(',', $_SESSION['article_id_arr']);
			$rg_key = array_search($article_id, $article_ids) + 1;
			$result['id'] = $article_ids[$rg_key] ? $article_ids[$rg_key] : 0;

			$cache_id = sprintf('%X', crc32($article_id . '-' . $_CFG['lang']));
			$rg_caches = get_article_caches($article_id); 
			$rg_html = CreateHtml("help.dwt", "help/".$article_id.".html", $cache_id);
			$result['content'] = $db->getOne("SELECT title FROM " . $ecs->table('article') . " WHERE article_id = '$article_id'");
		}else{
			$result['error'] = 1;
		}
		
		die($json->encode($result));
	}else{
		$_SESSION['article_id_arr'] = $article_id_arr = !empty($_REQUEST['article_id']) ? $_REQUEST['article_id'] : 0;
		$article_ids = explode(',', $article_id_arr);
		$smarty->assign('id', $article_ids[0]);
	}
}
/*专题详情页*/
elseif ($act == 'topic'){
	if($_REQUEST['is_json']){
		require(dirname(__FILE__) . '/includes/lib_comment.php');
		include_once('includes/cls_json.php');
		$json = new JSON;
		$result   = array('error' => 0, 'content' => '', 'id' => 0);

		$topic_id = $_REQUEST['id'] ? $_REQUEST['id'] : '0';

		if($topic_id){
			$templates = $db->getOne("SELECT template FROM ".$ecs->table('topic')." WHERE topic_id = '$topic_id' AND ".gmtime()." >= start_time AND ".gmtime()." <= end_time");
			$templates = empty($templates) ? 'topic.dwt' : $templates;

			$topic_ids = explode(',', $_SESSION['topic_id_arr']);
			$rg_key = array_search($topic_id, $topic_ids) + 1;
			$result['id'] = $topic_ids[$rg_key] ? $topic_ids[$rg_key] : 0;

			$cache_id = sprintf('%X', crc32($_SESSION['user_rank'] . '-' . $_CFG['lang'] . '-' . $topic_id));
			$rg_caches = get_topic_caches($topic_id); 
			$rg_html = CreateHtml($templates, "channel/".$topic_id.".html", $cache_id);
			$result['content'] = $db->getOne("SELECT title FROM " . $ecs->table('topic') . " WHERE topic_id = '$topic_id'");
		}else{
			$result['error'] = 1;
		}
		
		die($json->encode($result));
	}else{
		$_SESSION['topic_id_arr'] = $topic_id_arr = !empty($_REQUEST['topic_id']) ? $_REQUEST['topic_id'] : 0;
		$topic_ids = explode(',', $topic_id_arr);
		$smarty->assign('id', $topic_ids[0]);
	}
}

$smarty->display('rg_html.dwt');

/*------------------------------------------------------ */
//-- PRIVATE FUNCTIONS
/*------------------------------------------------------ */

function get_category_caches($cat_id = 0, $brand = 0, $min = 0, $max = 0, $size=10, $page=1, $sort='', $order='', $display = '', $filter_attr_str=0){
	$children = get_children($cat_id);
	$cat = get_cat_info($cat_id);

	$GLOBALS['smarty']->assign('keywords',    htmlspecialchars($cat['keywords']));
	$GLOBALS['smarty']->assign('description', htmlspecialchars($cat['cat_desc']));
	$GLOBALS['smarty']->assign('cat_style',   htmlspecialchars($cat['style']));
	$GLOBALS['smarty']->assign('parent_id',   htmlspecialchars($cat['parent_id']));
	$GLOBALS['smarty']->assign('cat_id', $cat_id);

	if ($cat['grade'] == 0  && $cat['parent_id'] != 0) $cat['grade'] = get_parent_grade($cat_id); 
	if ($cat['grade'] > 1){
		$sql = "SELECT min(g.shop_price) AS min, max(g.shop_price) as max FROM " . $GLOBALS['ecs']->table('goods'). " AS g WHERE ($children OR " . get_extension_goods($children) . ') AND g.is_delete = 0 AND g.is_on_sale = 1 AND g.is_alone_sale = 1  ';
		$row = $GLOBALS['db']->getRow($sql);

		$price_grade = 0.0001;
		for($i=-2; $i<= log10($row['max']); $i++){
			$price_grade *= 10;
		}

		$dx = ceil(($row['max'] - $row['min']) / ($cat['grade']) / $price_grade) * $price_grade;
		if($dx == 0) $dx = $price_grade; 

		for($i = 1; $row['min'] > $dx * $i; $i ++);

		for($j = 1; $row['min'] > $dx * ($i-1) + $price_grade * $j; $j++);
		$row['min'] = $dx * ($i-1) + $price_grade * ($j - 1);

		for(; $row['max'] >= $dx * $i; $i ++);
		$row['max'] = $dx * ($i) + $price_grade * ($j - 1);

		$sql = "SELECT (FLOOR((g.shop_price - $row[min]) / $dx)) AS sn, COUNT(*) AS goods_num FROM " . $GLOBALS['ecs']->table('goods') . " AS g WHERE ($children OR " . get_extension_goods($children) . ') AND g.is_delete = 0 AND g.is_on_sale = 1 AND g.is_alone_sale = 1 GROUP BY sn';
		$price_grade = $GLOBALS['db']->getAll($sql);
		foreach ($price_grade as $key=>$val){
			$temp_key = $key + 1;
			$price_grade[$temp_key]['goods_num'] = $val['goods_num'];
			$price_grade[$temp_key]['start'] = $row['min'] + round($dx * $val['sn']);
			$price_grade[$temp_key]['end'] = $row['min'] + round($dx * ($val['sn'] + 1));
			$price_grade[$temp_key]['price_range'] = $price_grade[$temp_key]['start'] . '&nbsp;-&nbsp;' . $price_grade[$temp_key]['end'];
			$price_grade[$temp_key]['formated_start'] = price_format($price_grade[$temp_key]['start']);
			$price_grade[$temp_key]['formated_end'] = price_format($price_grade[$temp_key]['end']);
			$price_grade[$temp_key]['url'] = build_uri('list', array('cid'=>$cat_id, 'bid'=>$brand, 'price_min'=>$price_grade[$temp_key]['start'], 'price_max'=> $price_grade[$temp_key]['end'], 'filter_attr'=>$filter_attr_str), $cat['cat_name']);

			if ($price_grade[$temp_key]['start'] == 0 && $price_grade[$temp_key]['end'] == 0){
				$price_grade[$temp_key]['selected'] = 1;
			}else{
				$price_grade[$temp_key]['selected'] = 0;
			}
		}
		$price_grade[0]['start'] = 0;
		$price_grade[0]['end'] = 0;
		$price_grade[0]['price_range'] = $GLOBALS['_LANG']['all_attribute'];
		$price_grade[0]['url'] = build_uri('list', array('cid'=>$cat_id, 'bid'=>$brand, 'price_min'=>0, 'price_max'=> 0, 'filter_attr'=>$filter_attr_str), $cat['cat_name']);
		$price_grade[0]['selected'] = 1;

		$GLOBALS['smarty']->assign('price_grade',     $price_grade);
	}
	$brand_have_logo = 0;
	$sql = "SELECT b.brand_id, b.brand_name, b.brand_logo, COUNT(*) AS goods_num FROM " . $GLOBALS['ecs']->table('brand') . "AS b, ". $GLOBALS['ecs']->table('goods') . " AS g LEFT JOIN ". $GLOBALS['ecs']->table('goods_cat') . " AS gc ON g.goods_id = gc.goods_id WHERE g.brand_id = b.brand_id AND ($children OR " . 'gc.cat_id ' . db_create_in(array_unique(array_merge(array($cat_id), array_keys(cat_list($cat_id, 0, false))))) . ") AND b.is_show = 1 AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 GROUP BY b.brand_id HAVING goods_num > 0 ORDER BY b.sort_order, b.brand_id ASC";
	$brands = $GLOBALS['db']->getAll($sql);
	foreach ($brands AS $key => $val){
		$temp_key = $key + 1;
		$brands[$temp_key]['brand_name'] = $val['brand_name'];
		$brands[$temp_key]['url'] = build_uri('list', array('cid' => $cat_id, 'bid' => $val['brand_id'], 'price_min'=>$price_min, 'price_max'=> $price_max, 'filter_attr'=>$filter_attr_str), $cat['cat_name']);
		$brands[$temp_key]['brand_id_ecshop68'] = $val['brand_id'];
		$brands[$temp_key]['brand_logo'] = $val['brand_logo'];
		if ($val['brand_logo']) $brand_have_logo=1;

		if ($brand == $brands[$key]['brand_id']){
			$brands[$temp_key]['selected'] = 1;
		}else{
			$brands[$temp_key]['selected'] = 0;
		}
	}
	$brand_zimu=array();
	foreach($brands AS $bkey=>$bval){
		$brands[$bkey]['pinyin'] = GetPinyin($bval['brand_name']);
		$brands[$bkey]['shouzimu'] =substr($brands[$bkey]['pinyin'],0,1);
		if (preg_match("/[a-zA-Z]/i", $brands[$bkey]['shouzimu'])){		
			$brands[$bkey]['shouzimu']=strtoupper($brands[$bkey]['shouzimu']);
			$brand_zimu[$brands[$bkey]['shouzimu']]=$brands[$bkey]['shouzimu'];			
		}else{
			$brand_zimu['其他']='其它'; 
			$brands[$bkey]['shouzimu']='其它';
		}		
	}
	ksort($brand_zimu);
	$GLOBALS['smarty']->assign('brand_zimu_ecshop68', $brand_zimu);
	$GLOBALS['smarty']->assign('url_no_price', build_uri('list', array('cid'=>$cat_id, 'bid'=>$brand,  'filter_attr'=>$filter_attr_str), $cat['cat_name']));

	$brands[0]['brand_name'] = $GLOBALS['_LANG']['all_attribute'];
	$brands[0]['url'] = build_uri('list', array('cid' => $cat_id, 'bid' => 0, 'price_min'=>$price_min, 'price_max'=> $price_max, 'filter_attr'=>$filter_attr_str), $cat['cat_name']);
	$brands[0]['selected'] = 1;

	$GLOBALS['smarty']->assign('brands', $brands);

	$ext = '';
	if ($cat['filter_attr'] > 0){
		$cat_filter_attr = explode(',', $cat['filter_attr']);
		$all_attr_list = array();
		foreach ($cat_filter_attr AS $key => $value){
			$sql = "SELECT a.attr_name FROM " . $GLOBALS['ecs']->table('attribute') . " AS a, " . $GLOBALS['ecs']->table('goods_attr') . " AS ga, " . $GLOBALS['ecs']->table('goods') . " AS g WHERE ($children OR " . get_extension_goods($children) . ") AND a.attr_id = ga.attr_id AND g.goods_id = ga.goods_id AND g.is_delete = 0 AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND a.attr_id='$value'";
			if($temp_name = $GLOBALS['db']->getOne($sql)){
				$all_attr_list[$key]['filter_attr_name'] = $temp_name;

				$sql = "SELECT a.attr_id, MIN(a.goods_attr_id ) AS goods_id, a.attr_value AS attr_value FROM " . $GLOBALS['ecs']->table('goods_attr') . " AS a, " . $GLOBALS['ecs']->table('goods') . " AS g WHERE ($children OR " . get_extension_goods($children) . ") AND g.goods_id = a.goods_id AND g.is_delete = 0 AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND a.attr_id='$value' GROUP BY a.attr_value";
				$attr_list = $GLOBALS['db']->getAll($sql);

				$temp_arrt_url_arr = array();

				for ($i = 0; $i < count($cat_filter_attr); $i++){
					$temp_arrt_url_arr[$i] = 0;
				}

				$temp_arrt_url_arr[$key] = 0;
				$temp_arrt_url = implode('.', $temp_arrt_url_arr);
				$all_attr_list[$key]['attr_list'][0]['attr_value'] = $GLOBALS['_LANG']['all_attribute'];
				$all_attr_list[$key]['attr_list'][0]['url'] = build_uri('list', array('cid'=>$cat_id, 'bid'=>$brand, 'price_min'=>$price_min, 'price_max'=>$price_max, 'filter_attr'=>$temp_arrt_url), $cat['cat_name']);
				$all_attr_list[$key]['attr_list'][0]['selected'] = 0;

				foreach ($attr_list as $k => $v){
					$temp_key = $k + 1;
					$temp_arrt_url_arr[$key] = $v['goods_id'];
					$temp_arrt_url = implode('.', $temp_arrt_url_arr);

					$all_attr_list[$key]['attr_list'][$temp_key]['attr_value'] = $v['attr_value'];
					$all_attr_list[$key]['attr_list'][$temp_key]['url'] = build_uri('list', array('cid'=>$cat_id, 'bid'=>$brand, 'price_min'=>$price_min, 'price_max'=>$price_max, 'filter_attr'=>$temp_arrt_url), $cat['cat_name']);

					$all_attr_list[$key]['attr_list'][$temp_key]['goods_id'] = $v['goods_id'];
					if($temp_name=='颜色'){
						$all_attr_list[$key]['attr_list'][$temp_key]['color_code']=$GLOBALS['db']->getOne("select color_code from ". $GLOBALS['ecs']->table('attribute_color') ." where color_name='$v[attr_value]' and attr_id='$v[attr_id]' ");
					}
					$filter_attr_name[$key][$v['goods_id']]=$v['attr_value'];

					$all_attr_list[$key]['attr_list'][$temp_key]['selected'] = 0;
				}
			}
		}
		$attr_group_more_txt = "";
		$attr_group_more_id =0;
		foreach ($all_attr_list AS $k_ecshop68=>$k_value)
		{
			if ($k_ecshop68 >1)
			{
				if ($attr_group_more_id <3)
				{
					$attr_group_more_txt .= ($attr_group_more_id ? "，" :"") . $k_value['filter_attr_name'];
				}
				$attr_group_more_id++;
			}
		}
		$GLOBALS['smarty']->assign('attr_group_more_count', count($all_attr_list));
		$GLOBALS['smarty']->assign('attr_group_more_txt', $attr_group_more_txt);
		
		$GLOBALS['smarty']->assign('filter_attr_list',  $all_attr_list);
	}
	assign_template('c', array($cat_id));

	$position = assign_ur_here($cat_id);
	$GLOBALS['smarty']->assign('page_title',       $position['title']);    // 页面标题
	$GLOBALS['smarty']->assign('ur_here',          $position['ur_here']);  // 当前位置
	$GLOBALS['smarty']->assign('current_cat_id', $cat_id);
	$catlist = array();
	foreach(get_parent_cats($cat_id) as $k=>$v){ $catlist[] = $v['cat_id']; }
	$GLOBALS['smarty']->assign('current_cat_pr_id',$catlist[count($catlist)-1]);
	$GLOBALS['smarty']->assign('categories',       get_categories_tree($cat_id)); // 分类树
	$GLOBALS['smarty']->assign('helps',            get_shop_help());              // 网店帮助
	$GLOBALS['smarty']->assign('top_goods',        get_top10());                  // 销售排行
	$GLOBALS['smarty']->assign('show_marketprice', $GLOBALS['_CFG']['show_marketprice']);
	$GLOBALS['smarty']->assign('category',         $cat_id);
    $GLOBALS['smarty']->assign('brand_id',         $brand);
    $GLOBALS['smarty']->assign('price_max',        $price_max);
    $GLOBALS['smarty']->assign('price_min',        $price_min);
    $GLOBALS['smarty']->assign('filter_attr',      $filter_attr_str);

	$brand_list = get_brands($cat_id, 'category');
	$GLOBALS['smarty']->assign('brand_list',      $brand_list);
	$GLOBALS['smarty']->assign('promotion_info', get_promotion_info());

	$GLOBALS['smarty']->assign('best_goods',      get_category_recommend_goods('best', $children, $brand, $price_min, $price_max, $ext));
    $GLOBALS['smarty']->assign('promotion_goods', get_category_recommend_goods('promote', $children, $brand, $price_min, $price_max, $ext));
    $GLOBALS['smarty']->assign('hot_goods',       get_category_recommend_goods('hot', $children, $brand, $price_min, $price_max, $ext));
	$GLOBALS['smarty']->assign('new_goods',       get_category_recommend_goods('new', $children, $brand, $price_min, $price_max, $ext));

    $count = get_cagtegory_goods_count($children, $brand, $price_min, $price_max, $ext);
	$max_page = ($count> 0) ? ceil($count / $size) : 1;
	if ($page > $max_page) $page = $max_page; 
    $goodslist = category_get_goods($children, $brand, $price_min, $price_max, $ext, $size, $page, $sort, $order);
	if($display == 'grid') if(count($goodslist) % 2 != 0) $goodslist[] = array();
	$GLOBALS['smarty']->assign('goods_list',       $goodslist);
	$GLOBALS['smarty']->assign('script_name', URL_PATH.'category');
	
	$GLOBALS['smarty']->assign('cat_name_curr', $cat['cat_name']);  
	$GLOBALS['smarty']->assign('brand_have_logo', $brand_have_logo);
	$GLOBALS['smarty']->assign('filter_attr_count',      count($all_attr_list));

	assign_pager('list', $cat_id, $count, $size, $sort, $order, $page, '', $brand, $price_min, $price_max, $display, $filter_attr_str);
	assign_dynamic('category');
}

function get_goods_caches($goods_id = 0){
	$GLOBALS['smarty']->assign('image_width',  $GLOBALS['_CFG']['image_width']);
    $GLOBALS['smarty']->assign('image_height', $GLOBALS['_CFG']['image_height']);
    $GLOBALS['smarty']->assign('helps',        get_shop_help()); // 网店帮助
    $GLOBALS['smarty']->assign('id',           $goods_id);
    $GLOBALS['smarty']->assign('type',         0);
    $GLOBALS['smarty']->assign('cfg',          $GLOBALS['_CFG']);
    $GLOBALS['smarty']->assign('promotion',       get_promotion_info($goods_id));//促销信息
    $GLOBALS['smarty']->assign('promotion_info', get_promotion_info());

    $goods = get_goods_info($goods_id);

	$service_zc_list = $GLOBALS['db']->getAll("SELECT * FROM " . $GLOBALS['ecs']->table('service_zc') . " WHERE " . db_create_in( explode(",", $goods['service_zc']), "id")); 
	$GLOBALS['smarty']->assign('service_zc_list',              $service_zc_list);
	
	$service_wz_list = $GLOBALS['db']->getAll( "SELECT * FROM " . $GLOBALS['ecs']->table('service_wz') . " WHERE " . db_create_in(explode(",", $goods['service_wz']),"wzs_id") );
	$GLOBALS['smarty']->assign('service_wz_list',              $service_wz_list);

	$rg_param = $GLOBALS['db']->getRow("SELECT * FROM " . $GLOBALS['ecs']->table('goods_param') . " WHERE goods_id = '$goods_id'");
	$basic_list = array();
	$basic_info = $GLOBALS['_LANG']['basic_info'];
	foreach($basic_info as $_k=>$_v){ $basic_list[] = array('id'=>$_k, 'name'=>$_v, 'value'=>$rg_param['basic_'.$_k]); }
	$GLOBALS['smarty']->assign('basic_list', $basic_list);

	$display_list = array();
	$display_info = $GLOBALS['_LANG']['display_info'];
	foreach($display_info as $_k=>$_v){ $display_list[] = array('id'=>$_k, 'name'=>$_v, 'value'=>$rg_param['display_'.$_k]); }
	$GLOBALS['smarty']->assign('display_list', $display_list);

	$digital_list = array();
	$digital_info = $GLOBALS['_LANG']['digital_info'];
	foreach($digital_info as $_k=>$_v){ $digital_list[] = array('id'=>$_k, 'name'=>$_v, 'value'=>$rg_param['digital_'.$_k]); }
	$GLOBALS['smarty']->assign('digital_list', $digital_list);
	
	$function_list = array();
	$function_info = $GLOBALS['_LANG']['function_info'];
	foreach($function_info as $_k=>$_v){ $function_list[] = array('id'=>$_k, 'name'=>$_v, 'value'=>$rg_param['function_'.$_k]); }
	$GLOBALS['smarty']->assign('function_list', $function_list);

	if ($goods['brand_id'] > 0) $goods['goods_brand_url'] = build_uri('brand', array('bid'=>$goods['brand_id']), $goods['goods_brand']); 


	$goods['goods_style_name'] = add_style($goods['goods_name'], $goods['goods_name_style']);

	if ($goods['bonus_type_id'] > 0){
		$time = gmtime();
		$sql = "SELECT type_money FROM " . $GLOBALS['ecs']->table('bonus_type') . " WHERE type_id = '$goods[bonus_type_id]' AND send_type = '" . SEND_BY_GOODS . "' AND send_start_date <= '$time' AND send_end_date >= '$time'";
		$goods['bonus_money'] = floatval($GLOBALS['db']->getOne($sql));
		if ($goods['bonus_money'] > 0) $goods['bonus_money'] = price_format($goods['bonus_money']); 
	}

	$GLOBALS['smarty']->assign('goods',              $goods);
	$GLOBALS['smarty']->assign('goods_id',           $goods['goods_id']);
	$GLOBALS['smarty']->assign('promote_end_time',   $goods['gmt_end_time']);
	$GLOBALS['smarty']->assign('categories',         get_categories_tree($goods['cat_id']));

	$GLOBALS['smarty']->assign('keywords',           htmlspecialchars($goods['keywords']));
	$GLOBALS['smarty']->assign('description',        htmlspecialchars($goods['goods_brief']));

	$catlist = array();
	foreach(get_parent_cats($goods['cat_id']) as $k=>$v){ $catlist[] = $v['cat_id']; }

	assign_template('c', $catlist);

	$prev_gid = $GLOBALS['db']->getOne("SELECT goods_id FROM " .$GLOBALS['ecs']->table('goods'). " WHERE cat_id='" . $goods['cat_id'] . "' AND goods_id > '" . $goods['goods_id'] . "' AND is_on_sale = 1 AND is_alone_sale = 1 AND is_delete = 0 LIMIT 1");
	if (!empty($prev_gid)){
		$prev_good['url'] = build_uri('goods', array('gid' => $prev_gid), $goods['goods_name']);
		$GLOBALS['smarty']->assign('prev_good', $prev_good);
	}

	$next_gid = $GLOBALS['db']->getOne("SELECT max(goods_id) FROM " . $GLOBALS['ecs']->table('goods') . " WHERE cat_id='".$goods['cat_id']."' AND goods_id < '".$goods['goods_id'] . "' AND is_on_sale = 1 AND is_alone_sale = 1 AND is_delete = 0");
	if (!empty($next_gid)){
		$next_good['url'] = build_uri('goods', array('gid' => $next_gid), $goods['goods_name']);
		$GLOBALS['smarty']->assign('next_good', $next_good);
	}

	$position = assign_ur_here($goods['cat_id'], $goods['goods_name']);
	$GLOBALS['smarty']->assign('page_title',          $position['title']);                    // 页面标题
	$GLOBALS['smarty']->assign('ur_here',             $position['ur_here']);                  // 当前位置

	$properties = get_goods_properties($goods_id);  // 获得商品的规格和属性
	$GLOBALS['smarty']->assign('properties',          $properties['pro']);                              // 商品属性
	$GLOBALS['smarty']->assign('specification',       $properties['spe']);                              // 商品规格
	$GLOBALS['smarty']->assign('attribute_linked',    get_same_attribute_goods($properties));           // 相同属性的关联商品

	$GLOBALS['smarty']->assign('related_goods',       get_linked_goods($goods_id));                                   // 关联商品
	$GLOBALS['smarty']->assign('goods_article_list',  get_linked_articles($goods_id));                  // 关联文章
	$GLOBALS['smarty']->assign('fittings',            get_goods_fittings(array($goods_id)));                   // 配件
	$GLOBALS['smarty']->assign('rank_prices',         get_user_rank_prices($goods_id, $goods['shop_price']));    // 会员等级价格
	$GLOBALS['smarty']->assign('pictures',            get_goods_gallery($goods_id));                    // 商品相册
	$GLOBALS['smarty']->assign('bought_goods',        get_also_bought($goods_id));                      // 购买了该商品的用户还购买了哪些商品
	$GLOBALS['smarty']->assign('goods_rank',          get_goods_rank($goods_id));                       // 商品的销售排名

	$GLOBALS['smarty']->assign('gift_list',           get_goods_fittings(array($goods_id),1));         // rg808赠品
	$GLOBALS['smarty']->assign('addbuy_list',         get_goods_fittings(array($goods_id),0,1));     // rg808加购商品
	
	$count = $GLOBALS['db']->getOne("SELECT COUNT(*) FROM " . $GLOBALS['ecs']->table('comment') . " where comment_type=0 and id_value ='$goods_id' and status=1");
	$GLOBALS['smarty']->assign('review_count',       $count); 

	$tag_array = get_tags($goods_id);
	$GLOBALS['smarty']->assign('tags',                $tag_array);                                       // 商品的标记

	//获取关联礼包
	$package_goods_list = get_package_goods_list($goods['goods_id']);
	$GLOBALS['smarty']->assign('package_goods_list',$package_goods_list);    // 获取关联礼包

	$package_goods_list_120 = get_package_goods_list_120($goods['goods_id']);
	$GLOBALS['smarty']->assign('package_goods_list_120',$package_goods_list_120);    // 获取关联礼包

	assign_dynamic('goods');
	$volume_price_list = get_volume_price_list($goods['goods_id'], '1');
	$GLOBALS['smarty']->assign('volume_price_list',$volume_price_list);    // 商品优惠价格区间

	include_once ( 'themes/'.$GLOBALS['_CFG']['template'].'/plugin_comments/plugin_comments.php');
	$GLOBALS['smarty']->assign("comment_score", get_comment_score($goods['goods_id']));
	
	$rank_num['rank_a'] = $GLOBALS['db']->getOne("SELECT COUNT(*) AS num FROM ".$GLOBALS['ecs']->table('comment')." WHERE id_value = '$goods_id' AND status = 1 AND comment_rank in (5,4)");
	$rank_num['rank_b'] = $GLOBALS['db']->getOne("SELECT COUNT(*) AS num FROM ".$GLOBALS['ecs']->table('comment')." WHERE id_value = '$goods_id' AND status = 1 AND comment_rank in (3,2)");
	$rank_num['rank_c'] = $GLOBALS['db']->getOne("SELECT COUNT(*) AS num FROM ".$GLOBALS['ecs']->table('comment')." WHERE id_value = '$goods_id' AND status = 1 AND comment_rank = 1");
	$rank_num['rank_total'] = $rank_num['rank_a'] + $rank_num['rank_b'] + $rank_num['rank_c'];
	$rank_num['rank_pa'] = ($rank_num['rank_a'] > 0) ? round(($rank_num['rank_a'] / $rank_num['rank_total']) * 100,1) : 0;
	$rank_num['rank_pb'] = ($rank_num['rank_b'] > 0) ? round(($rank_num['rank_b'] / $rank_num['rank_total']) * 100,1) : 0;
	$rank_num['rank_pc'] = ($rank_num['rank_c'] > 0) ? round(($rank_num['rank_c'] / $rank_num['rank_total']) * 100,1) : 0;
	$rank_num['shaidan_num'] = $GLOBALS['db']->getOne("SELECT COUNT(*) AS num FROM ".$GLOBALS['ecs']->table('shaidan')." WHERE goods_id = '$goods_id' AND status = 1");
	$GLOBALS['smarty']->assign('rank_num',$rank_num);
	
	$tag_arr = array();
	$comment_tags = array();
	$res = $GLOBALS['db']->getAll("SELECT * FROM ".$GLOBALS['ecs']->table('goods_tag')." WHERE goods_id = '$goods_id' AND state = 1");	
	foreach ($res as $v){
		$v['tag_num'] = $GLOBALS['db']->getOne("SELECT COUNT(*) AS num FROM ".$GLOBALS['ecs']->table('comment')." WHERE id_value = '$goods_id' AND status = 1 AND FIND_IN_SET($v[tag_id],comment_tag)");
		$tag_arr[] = $v;	
	}
	$tag_arr = array_sort($tag_arr,'tag_num','desc');
	foreach ($tag_arr as $key => $val){
		if ($GLOBALS['_CFG']['tag_show_num'] > 0){
			if (($key + 1) <= $GLOBALS['_CFG']['tag_show_num']) $comment_tags[] = $val;
		}else{
			$comment_tags[] = $val;	
		}
	}
	$GLOBALS['smarty']->assign('comment_tags',$comment_tags);

	$GLOBALS['smarty']->assign('now_time',  gmtime());           // 当前系统时间
}
function get_brand_caches($brand_id = 0, $brand = 0, $size=10, $page=1, $sort='', $order='', $display = '', $cate=0){
	$brand_info = get_brand_info($brand_id);
    $GLOBALS['smarty']->assign('keywords',    htmlspecialchars($brand_info['brand_desc']));
    $GLOBALS['smarty']->assign('description', htmlspecialchars($brand_info['brand_desc']));

    assign_template();
    $position = assign_ur_here($cate, $brand_info['brand_name']);
    $GLOBALS['smarty']->assign('page_title',     $position['title']);   // 页面标题
    $GLOBALS['smarty']->assign('ur_here',        $position['ur_here']); // 当前位置
    $GLOBALS['smarty']->assign('brand_id',       $brand_id);
    $GLOBALS['smarty']->assign('category',       $cate);

    $GLOBALS['smarty']->assign('categories',     get_categories_tree());        // 分类树
    $GLOBALS['smarty']->assign('helps',          get_shop_help());              // 网店帮助
    $GLOBALS['smarty']->assign('top_goods',      get_top10());                  // 销售排行
    $GLOBALS['smarty']->assign('show_marketprice', $GLOBALS['_CFG']['show_marketprice']);
    $GLOBALS['smarty']->assign('brand_cat_list', brand_related_cat($brand_id)); // 相关分类

    $GLOBALS['smarty']->assign('best_goods',      brand_recommend_goods('best', $brand_id, $cate));
    $GLOBALS['smarty']->assign('promotion_goods', brand_recommend_goods('promote', $brand_id, $cate));
    $GLOBALS['smarty']->assign('brand',           $brand_info);
    $GLOBALS['smarty']->assign('promotion_info', get_promotion_info());

    $count = goods_count_by_brand($brand_id, $cate);

    $goodslist = brand_get_goods($brand_id, $cate, $size, $page, $sort, $order);

    if($display == 'grid'){
        if(count($goodslist) % 2 != 0) $goodslist[] = array(); 
    }
    $GLOBALS['smarty']->assign('goods_list',      $goodslist);
    $GLOBALS['smarty']->assign('script_name', 'brand');

    assign_pager('brand',              $cate, $count, $size, $sort, $order, $page, '', $brand_id, 0, 0, $display); // 分页
    assign_dynamic('brand'); // 动态内容
}

function get_article_cat_caches($cat_id = 0, $page = 1){
	assign_template('a', array($cat_id));
    $position = assign_ur_here($cat_id);
    $GLOBALS['smarty']->assign('page_title',           $position['title']);     // 页面标题
    $GLOBALS['smarty']->assign('ur_here',              $position['ur_here']);   // 当前位置

    $GLOBALS['smarty']->assign('categories',           get_categories_tree(0)); // 分类树
    $GLOBALS['smarty']->assign('article_categories',   article_categories_tree($cat_id)); //文章分类树
    $GLOBALS['smarty']->assign('helps',                get_shop_help());        // 网店帮助
    $GLOBALS['smarty']->assign('top_goods',            get_top10());            // 销售排行

    $GLOBALS['smarty']->assign('best_goods',           get_recommend_goods('best'));
    $GLOBALS['smarty']->assign('new_goods',            get_recommend_goods('new'));
    $GLOBALS['smarty']->assign('hot_goods',            get_recommend_goods('hot'));
    $GLOBALS['smarty']->assign('promotion_goods',      get_promote_goods());
    $GLOBALS['smarty']->assign('promotion_info', get_promotion_info());

    $meta = $GLOBALS['db']->getRow("SELECT keywords, cat_desc FROM " . $GLOBALS['ecs']->table('article_cat') . " WHERE cat_id = '$cat_id'");
    $GLOBALS['smarty']->assign('keywords',    htmlspecialchars($meta['keywords']));
    $GLOBALS['smarty']->assign('description', htmlspecialchars($meta['cat_desc']));

    $size = isset($GLOBALS['_CFG']['article_page_size']) && intval($GLOBALS['_CFG']['article_page_size']) > 0 ? intval($GLOBALS['_CFG']['article_page_size']) : 20;
    $count  = get_article_count($cat_id);
    $pages  = ($count > 0) ? ceil($count / $size) : 1;

    if ($page > $pages) $page = $pages; 
    $pager['search']['id'] = $cat_id;
    $keywords = '';
    $goon_keywords = ''; //继续传递的搜索关键词

    $GLOBALS['smarty']->assign('artciles_list',    get_cat_articles($cat_id, $page, $size ,$keywords));
    $GLOBALS['smarty']->assign('cat_id',    $cat_id);
    /* 分页 */
    assign_pager('news', $cat_id, $count, $size, '', '', $page, $goon_keywords);
    assign_dynamic('article_cat');
}

function get_article_caches($article_id = 0){
	$article = get_article_info($article_id);

    $GLOBALS['smarty']->assign('article_categories',   article_categories_tree($article_id)); //文章分类树
    $GLOBALS['smarty']->assign('categories',       get_categories_tree());  // 分类树
    $GLOBALS['smarty']->assign('helps',            get_shop_help()); // 网店帮助
    $GLOBALS['smarty']->assign('top_goods',        get_top10());    // 销售排行
    $GLOBALS['smarty']->assign('best_goods',       get_recommend_goods('best'));       // 推荐商品
    $GLOBALS['smarty']->assign('new_goods',        get_recommend_goods('new'));        // 最新商品
    $GLOBALS['smarty']->assign('hot_goods',        get_recommend_goods('hot'));        // 热点文章
    $GLOBALS['smarty']->assign('promotion_goods',  get_promote_goods());    // 特价商品
    $GLOBALS['smarty']->assign('related_goods',    article_related_goods($article_id));
    $GLOBALS['smarty']->assign('id',               $article_id);
    $GLOBALS['smarty']->assign('username',         $_SESSION['user_name']);
    $GLOBALS['smarty']->assign('email',            $_SESSION['email']);
    $GLOBALS['smarty']->assign('type',            '1');
    $GLOBALS['smarty']->assign('promotion_info', get_promotion_info());

	$GLOBALS['smarty']->assign( 'article_wzgg_list', get_article_new(array(12),'art_cat',10) );

    if ((intval($GLOBALS['_CFG']['captcha']) & CAPTCHA_COMMENT) && gd_version() > 0)
    {
        $GLOBALS['smarty']->assign('enabled_captcha', 1);
        $GLOBALS['smarty']->assign('rand',            mt_rand());
    }

    $GLOBALS['smarty']->assign('article',      $article);
    $GLOBALS['smarty']->assign('keywords',     htmlspecialchars($article['keywords']));
    $GLOBALS['smarty']->assign('description', htmlspecialchars($article['description']));

    $catlist = array();
    foreach(get_article_parent_cats($article['cat_id']) as $k=>$v){
        $catlist[] = $v['cat_id'];
    }

    assign_template('a', $catlist);

    $position = assign_ur_here($article['cat_id'], $article['title']);
    $GLOBALS['smarty']->assign('page_title',   $position['title']);    // 页面标题
    $GLOBALS['smarty']->assign('ur_here',      $position['ur_here']);  // 当前位置
    $GLOBALS['smarty']->assign('comment_type', 1);
	$GLOBALS['smarty']->assign('topcatid',array_pop($catlist));

    $sql = "SELECT a.goods_id, g.goods_name FROM " . $GLOBALS['ecs']->table('goods_article') . " AS a, " . $GLOBALS['ecs']->table('goods') . " AS g WHERE a.goods_id = g.goods_id AND a.article_id = '$article_id' ";
    $GLOBALS['smarty']->assign('goods_list', $GLOBALS['db']->getAll($sql));

    $next_article = $GLOBALS['db']->getRow("SELECT article_id, title FROM " .$GLOBALS['ecs']->table('article'). " WHERE article_id > '$article_id' AND cat_id='$article[cat_id]' AND is_open=1 LIMIT 1");
    if (!empty($next_article)){
        $next_article['url'] = build_uri('article', array('aid'=>$next_article['article_id']), $next_article['title']);
        $GLOBALS['smarty']->assign('next_article', $next_article);
    }

    $prev_aid = $GLOBALS['db']->getOne("SELECT max(article_id) FROM " . $GLOBALS['ecs']->table('article') . " WHERE article_id < '$article_id' AND cat_id='$article[cat_id]' AND is_open=1");
    if (!empty($prev_aid)){
        $prev_article = $GLOBALS['db']->getRow("SELECT article_id, title FROM " .$GLOBALS['ecs']->table('article'). " WHERE article_id = $prev_aid");
        $prev_article['url'] = build_uri('article', array('aid'=>$prev_article['article_id']), $prev_article['title']);
        $GLOBALS['smarty']->assign('prev_article', $prev_article);
    }

    assign_dynamic('article');
}

function get_topic_caches($topic_id = 0){
    $topic = $GLOBALS['db']->getRow("SELECT * FROM " . $GLOBALS['ecs']->table('topic') . " WHERE topic_id = '$topic_id'");

    $topic['data'] = addcslashes($topic['data'], "'");
    $tmp = @unserialize($topic["data"]);
    $arr = (array)$tmp;
    $goods_id = array();
    foreach ($arr AS $key=>$value){
        foreach($value AS $k => $val){
            $opt = explode('|', $val);
            $arr[$key][$k] = $opt[1];
            $goods_id[] = $opt[1];
        }
    }
    $sql = "SELECT g.goods_id, g.goods_name, g.goods_name_style, g.market_price, g.is_new, g.is_best, g.is_hot, g.shop_price AS org_price, IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS shop_price, g.promote_price, g.promote_start_date, g.promote_end_date, g.goods_brief, g.goods_thumb , g.goods_img FROM " . $GLOBALS['ecs']->table('goods') . ' AS g LEFT JOIN ' . $GLOBALS['ecs']->table('member_price') . " AS mp ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' WHERE " . db_create_in($goods_id, 'g.goods_id');

    $res = $GLOBALS['db']->query($sql);
    $sort_goods_arr = array();
    while ($row = $GLOBALS['db']->fetchRow($res)){
        if ($row['promote_price'] > 0){
            $promote_price = bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']);
            $row['promote_price'] = $promote_price > 0 ? price_format($promote_price) : '';
        }else{
            $row['promote_price'] = '';
        }

        if ($row['shop_price'] > 0){
            $row['shop_price'] =  price_format($row['shop_price']);
        }else{
            $row['shop_price'] = '';
        }

        $row['url']              = build_uri('goods', array('gid'=>$row['goods_id']), $row['goods_name']);
        $row['goods_style_name'] = add_style($row['goods_name'], $row['goods_name_style']);
        $row['short_name']       = $GLOBALS['_CFG']['goods_name_length'] > 0 ? sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name'];
        $row['goods_thumb']      = get_image_path($row['goods_id'], $row['goods_thumb'], true);
        $row['short_style_name'] = add_style($row['short_name'], $row['goods_name_style']);

        foreach ($arr AS $key => $value){
            foreach ($value AS $val){
                if ($val == $row['goods_id']){
                    $key = $key == 'default' ? $GLOBALS['_LANG']['all_goods'] : $key;
                    $sort_goods_arr[$key][] = $row;
                }
            }
        }
    }

    assign_template();
    $position = assign_ur_here();
    $GLOBALS['smarty']->assign('page_title',       $position['title']);       // 页面标题
    $GLOBALS['smarty']->assign('ur_here',          $position['ur_here'] . '> ' . $topic['title']);     // 当前位置
    $GLOBALS['smarty']->assign('show_marketprice', $GLOBALS['_CFG']['show_marketprice']);
    $GLOBALS['smarty']->assign('sort_goods_arr',   $sort_goods_arr);          // 商品列表
    $GLOBALS['smarty']->assign('topic',            $topic);                   // 专题信息
    $GLOBALS['smarty']->assign('keywords',         $topic['keywords']);       // 专题信息
    $GLOBALS['smarty']->assign('description',      $topic['description']);    // 专题信息
    $GLOBALS['smarty']->assign('title_pic',        $topic['title_pic']);      // 分类标题图片地址
    $GLOBALS['smarty']->assign('base_style',       '#' . $topic['base_style']);     // 基本风格样式颜色
}

function get_flash_xml(){
    $flashdb = array();
    if (file_exists(ROOT_PATH . DATA_DIR . '/flash_data.xml')){
        if (!preg_match_all('/item_url="([^"]+)"\slink="([^"]+)"\stext="([^"]*)"\ssort="([^"]*)"/', file_get_contents(ROOT_PATH . DATA_DIR . '/flash_data.xml'), $t, PREG_SET_ORDER)){
            preg_match_all('/item_url="([^"]+)"\slink="([^"]+)"\stext="([^"]*)"/', file_get_contents(ROOT_PATH . DATA_DIR . '/flash_data.xml'), $t, PREG_SET_ORDER);
        }
        if (!empty($t)){
            foreach ($t as $key => $val){
                $val[4] = isset($val[4]) ? $val[4] : 0;
                $flashdb[] = array('src'=>$val[1],'url'=>$val[2],'text'=>$val[3],'sort'=>$val[4]);
            }
        }
    }
    return $flashdb;
}

function index_get_links(){
    $sql = 'SELECT link_logo, link_name, link_url FROM ' . $GLOBALS['ecs']->table('friend_link') . ' ORDER BY show_order';
    $res = $GLOBALS['db']->getAll($sql);
    $links['img'] = $links['txt'] = array();
    foreach ($res AS $row){
        if (!empty($row['link_logo'])){
            $links['img'][] = array('name' => $row['link_name'], 'url'  => $row['link_url'], 'logo' => $row['link_logo']);
        }else{
            $links['txt'][] = array('name' => $row['link_name'], 'url'  => $row['link_url']);
        }
    }
    return $links;
}

/* 获得分类的信息 */
function get_cat_info($cat_id){
    return $GLOBALS['db']->getRow('SELECT cat_name, keywords, cat_desc, style, grade, filter_attr, parent_id FROM ' . $GLOBALS['ecs']->table('category') . " WHERE cat_id = '$cat_id'");
}

/* 取得最近的上级分类的grade值 */
function get_parent_grade($cat_id){
    static $res = NULL;

    if ($res === NULL){
        $data = read_static_cache('cat_parent_grade');
        if ($data === false){
            $sql = "SELECT parent_id, cat_id, grade FROM " . $GLOBALS['ecs']->table('category');
            $res = $GLOBALS['db']->getAll($sql);
            write_static_cache('cat_parent_grade', $res);
        }else{
            $res = $data;
        }
    }
    if (!$res) return 0; 

    $parent_arr = array();
    $grade_arr = array();
    foreach ($res as $val){
        $parent_arr[$val['cat_id']] = $val['parent_id'];
        $grade_arr[$val['cat_id']] = $val['grade'];
    }
    while ($parent_arr[$cat_id] >0 && $grade_arr[$cat_id] == 0){
        $cat_id = $parent_arr[$cat_id];
    }
    return $grade_arr[$cat_id];
}
/* 获得分类下的商品 */
function category_get_goods($children, $brand = 0, $min = 0, $max = 0, $ext='', $size=10, $page=1, $sort='', $order=''){
    $display = $GLOBALS['display'];
    $where = "g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 AND ($children OR " . get_extension_goods($children) . ')';

    if ($brand > 0){
		if (strstr($brand, '-')){
			$brand_sql =str_replace("-", ",", $brand);
			$where .=  "AND g.brand_id in ($brand_sql) ";
		}else{
			$where .=  "AND g.brand_id=$brand ";
		}
    }

    if ($min > 0) $where .= " AND g.shop_price >= $min "; 
    if ($max > 0) $where .= " AND g.shop_price <= $max "; 

    /* 获得商品列表 */
    $sql = "SELECT g.goods_id, g.goods_name, g.goods_name_style, g.click_count, g.market_price, g.is_new, g.is_best, g.is_hot, g.shop_price AS org_price, IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS shop_price, g.promote_price, g.goods_type, g.promote_start_date, g.promote_end_date, g.goods_brief, g.goods_thumb , g.goods_img FROM " . $GLOBALS['ecs']->table('goods') . " AS g LEFT JOIN " . $GLOBALS['ecs']->table('member_price') . " AS mp ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' WHERE $where $ext ORDER BY $sort $order";
	if ($sort=='salenum'){
		$sql = "SELECT SUM(o.goods_number) as salenum, g.goods_id, g.goods_name, g.goods_name_style, g.market_price, g.is_new, g.is_best, g.is_hot, g.shop_price AS org_price, IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS shop_price, g.promote_price, g.goods_type, g.promote_start_date, g.promote_end_date, g.goods_brief, g.goods_thumb , g.goods_img FROM " . $GLOBALS['ecs']->table('goods') . " AS g LEFT JOIN " . $GLOBALS['ecs']->table('member_price') . " AS mp ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' LEFT JOIN " . $GLOBALS['ecs']->table('order_goods') .  " as o ON o.goods_id = g.goods_id " . "WHERE $where $ext group by g.goods_id ORDER BY $sort $order";
	}
    $res = $GLOBALS['db']->selectLimit($sql, $size, ($page - 1) * $size);

    $arr = array();
    while ($row = $GLOBALS['db']->fetchRow($res)){
        if ($row['promote_price'] > 0){
            $promote_price = bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']);
        }else{
            $promote_price = 0;
        }

        /* 处理商品水印图片 */
        $watermark_img = '';
        if ($promote_price != 0){
            $watermark_img = "watermark_promote_small";
        }elseif ($row['is_new'] != 0){
            $watermark_img = "watermark_new_small";
        }elseif ($row['is_best'] != 0){
            $watermark_img = "watermark_best_small";
        }elseif ($row['is_hot'] != 0){
            $watermark_img = 'watermark_hot_small';
        }

        if ($watermark_img != '') $arr[$row['goods_id']]['watermark_img'] =  $watermark_img; 

        $arr[$row['goods_id']]['goods_id']         = $row['goods_id'];
        if($display == 'grid'){
            $arr[$row['goods_id']]['goods_name']       = $GLOBALS['_CFG']['goods_name_length'] > 0 ? sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name'];
        }else{
            $arr[$row['goods_id']]['goods_name']       = $row['goods_name'];
        }
        $arr[$row['goods_id']]['name']             = $row['goods_name'];
		$arr[$row['goods_id']]['is_new']             = $row['is_new'];
		$arr[$row['goods_id']]['is_hot']             = $row['is_hot'];
		$arr[$row['goods_id']]['is_best']             = $row['is_best'];
        $arr[$row['goods_id']]['goods_brief']      = $row['goods_brief'];
        $arr[$row['goods_id']]['goods_style_name'] = add_style($row['goods_name'],$row['goods_name_style']);
        $arr[$row['goods_id']]['market_price']     = price_format($row['market_price']);
		
		$products = $GLOBALS['db']->getRow("SELECT * FROM " . $GLOBALS['ecs']->table('products') . " WHERE goods_id = '".$row['goods_id']."' order by product_price asc");
        $arr[$row['goods_id']]['shop_price']       = price_format($products['product_price'] ? $products['product_price'] : $row['shop_price']);

        $arr[$row['goods_id']]['type']             = $row['goods_type'];
        $arr[$row['goods_id']]['promote_price']    = ($promote_price > 0) ? price_format($promote_price) : '';
        $arr[$row['goods_id']]['goods_thumb']      = get_image_path($row['goods_id'], $row['goods_thumb'], true);
        $arr[$row['goods_id']]['goods_img']        = get_image_path($row['goods_id'], $row['goods_img']);
        $arr[$row['goods_id']]['url']              = build_uri('goods', array('gid'=>$row['goods_id']), $row['goods_name']);
		$arr[$row['goods_id']]['comment_count']    = get_comment_count($row['goods_id']);
		$arr[$row['goods_id']]['count']            = selled_count($row['goods_id']);
		$arr[$row['goods_id']]['click_count']      = $row['click_count'];
    }
    return $arr;
}
/* 获得分类下的商品总数 */
function get_cagtegory_goods_count($children, $brand = 0, $min = 0, $max = 0, $ext=''){
    $where  = "g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 AND ($children OR " . get_extension_goods($children) . ')';

    if ($brand > 0){
		if (strstr($brand, '-')){
			$brand_sql =str_replace("-", ",", $brand);
			$where .=  "AND g.brand_id in ($brand_sql) ";
		}else{
			$where .=  "AND g.brand_id=$brand ";
		}
    }

    if ($min > 0) $where .= " AND g.shop_price >= $min "; 
    if ($max > 0) $where .= " AND g.shop_price <= $max "; 

    return $GLOBALS['db']->getOne('SELECT COUNT(*) FROM ' . $GLOBALS['ecs']->table('goods') . " AS g WHERE $where $ext");
}

/* 获得指定商品的关联商品 */
function get_linked_goods($goods_id){
    $sql = "SELECT g.goods_id, g.goods_name, g.goods_thumb, g.goods_img, g.shop_price AS org_price, IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS shop_price, g.market_price, g.promote_price, g.promote_start_date, g.promote_end_date FROM " . $GLOBALS['ecs']->table('link_goods') . " lg LEFT JOIN " . $GLOBALS['ecs']->table('goods') . " AS g ON g.goods_id = lg.link_goods_id LEFT JOIN " . $GLOBALS['ecs']->table('member_price') . " AS mp ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' WHERE lg.goods_id = '$goods_id' AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 LIMIT " . $GLOBALS['_CFG']['related_goods_number'];
    $res = $GLOBALS['db']->query($sql);

    $arr = array();
    while ($row = $GLOBALS['db']->fetchRow($res)){
        $arr[$row['goods_id']]['goods_id']     = $row['goods_id'];
        $arr[$row['goods_id']]['goods_name']   = $row['goods_name'];
        $arr[$row['goods_id']]['short_name']   = $GLOBALS['_CFG']['goods_name_length'] > 0 ? sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name'];
        $arr[$row['goods_id']]['goods_thumb']  = get_image_path($row['goods_id'], $row['goods_thumb'], true);
        $arr[$row['goods_id']]['goods_img']    = get_image_path($row['goods_id'], $row['goods_img']);
        $arr[$row['goods_id']]['market_price'] = price_format($row['market_price']);
        $arr[$row['goods_id']]['shop_price']   = price_format($row['shop_price']);
        $arr[$row['goods_id']]['url']          = build_uri('goods', array('gid'=>$row['goods_id']), $row['goods_name']);

        if ($row['promote_price'] > 0){
            $arr[$row['goods_id']]['promote_price'] = bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']);
            $arr[$row['goods_id']]['formated_promote_price'] = price_format($arr[$row['goods_id']]['promote_price']);
        }else{
            $arr[$row['goods_id']]['promote_price'] = 0;
        }
    }
    return $arr;
}
/* 获得指定商品的关联文章 */
function get_linked_articles($goods_id){
    $sql = 'SELECT a.article_id, a.title, a.file_url, a.open_type, a.add_time FROM ' . $GLOBALS['ecs']->table('goods_article') . ' AS g, ' . $GLOBALS['ecs']->table('article') . " AS a WHERE g.article_id = a.article_id AND g.goods_id = '$goods_id' AND a.is_open = 1 ORDER BY a.add_time DESC";
    $res = $GLOBALS['db']->query($sql);

    $arr = array();
    while ($row = $GLOBALS['db']->fetchRow($res)){
        $row['url']         = $row['open_type'] != 1 ? build_uri('article', array('aid'=>$row['article_id']), $row['title']) : trim($row['file_url']);
        $row['add_time']    = local_date($GLOBALS['_CFG']['date_format'], $row['add_time']);
        $row['short_title'] = $GLOBALS['_CFG']['article_title_length'] > 0 ? sub_str($row['title'], $GLOBALS['_CFG']['article_title_length']) : $row['title'];

        $arr[] = $row;
    }
    return $arr;
}
/* 获得指定商品的各会员等级对应的价格 */
function get_user_rank_prices($goods_id, $shop_price){
    $sql = "SELECT rank_id, IFNULL(mp.user_price, r.discount * $shop_price / 100) AS price, r.rank_name, r.discount FROM " . $GLOBALS['ecs']->table('user_rank') . " AS r LEFT JOIN " . $GLOBALS['ecs']->table('member_price') . " AS mp ON mp.goods_id = '$goods_id' AND mp.user_rank = r.rank_id WHERE r.show_price = 1 OR r.rank_id = '$_SESSION[user_rank]'";
    $res = $GLOBALS['db']->query($sql);

    $arr = array();
    while ($row = $GLOBALS['db']->fetchRow($res)){
        $arr[$row['rank_id']] = array( 'rank_name' => htmlspecialchars($row['rank_name']), 'price'     => price_format($row['price']));
    }
    return $arr;
}
/* 获得购买过该商品的人还买过的商品 */
function get_also_bought($goods_id){
    $sql = 'SELECT COUNT(b.goods_id ) AS num, g.goods_id, g.goods_name, g.goods_thumb, g.goods_img, g.shop_price, g.promote_price, g.promote_start_date, g.promote_end_date FROM ' . $GLOBALS['ecs']->table('order_goods') . ' AS a LEFT JOIN ' . $GLOBALS['ecs']->table('order_goods') . ' AS b ON b.order_id = a.order_id LEFT JOIN ' . $GLOBALS['ecs']->table('goods') . " AS g ON g.goods_id = b.goods_id WHERE a.goods_id = '$goods_id' AND b.goods_id <> '$goods_id' AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 GROUP BY b.goods_id ORDER BY num DESC LIMIT " . $GLOBALS['_CFG']['bought_goods'];
    $res = $GLOBALS['db']->query($sql);

    $key = 0;
    $arr = array();
    while ($row = $GLOBALS['db']->fetchRow($res)){
        $arr[$key]['goods_id']    = $row['goods_id'];
        $arr[$key]['goods_name']  = $row['goods_name'];
        $arr[$key]['short_name']  = $GLOBALS['_CFG']['goods_name_length'] > 0 ? sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name'];
        $arr[$key]['goods_thumb'] = get_image_path($row['goods_id'], $row['goods_thumb'], true);
        $arr[$key]['goods_img']   = get_image_path($row['goods_id'], $row['goods_img']);
        $arr[$key]['shop_price']  = price_format($row['shop_price']);
        $arr[$key]['url']         = build_uri('goods', array('gid'=>$row['goods_id']), $row['goods_name']);

        if ($row['promote_price'] > 0){
            $arr[$key]['promote_price'] = bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']);
            $arr[$key]['formated_promote_price'] = price_format($arr[$key]['promote_price']);
        }else{
            $arr[$key]['promote_price'] = 0;
        }
        $key++;
    }
    return $arr;
}
/* 获得指定商品的销售排名 */
function get_goods_rank($goods_id){
    $period = intval($GLOBALS['_CFG']['top10_time']);
    if ($period == 1){
        $ext = " AND o.add_time > '" . local_strtotime('-1 years') . "'";
    }elseif ($period == 2){
        $ext = " AND o.add_time > '" . local_strtotime('-6 months') . "'";
    }elseif ($period == 3){
        $ext = " AND o.add_time > '" . local_strtotime('-3 months') . "'";
    }elseif ($period == 4){
        $ext = " AND o.add_time > '" . local_strtotime('-1 months') . "'";
    }else{
        $ext = '';
    }

    $sql = 'SELECT IFNULL(SUM(g.goods_number), 0) FROM ' . $GLOBALS['ecs']->table('order_info') . ' AS o, ' . $GLOBALS['ecs']->table('order_goods') . " AS g WHERE o.order_id = g.order_id AND o.order_status = '" . OS_CONFIRMED . "' AND o.shipping_status " . db_create_in(array(SS_SHIPPED, SS_RECEIVED)) . " AND o.pay_status " . db_create_in(array(PS_PAYED, PS_PAYING)) . " AND g.goods_id = '$goods_id'" . $ext;
    $sales_count = $GLOBALS['db']->getOne($sql);

    if ($sales_count > 0){
        $sql = 'SELECT DISTINCT SUM(goods_number) AS num FROM ' . $GLOBALS['ecs']->table('order_info') . ' AS o, ' . $GLOBALS['ecs']->table('order_goods') . " AS g WHERE o.order_id = g.order_id AND o.order_status = '" . OS_CONFIRMED . "' AND o.shipping_status " . db_create_in(array(SS_SHIPPED, SS_RECEIVED)) . " AND o.pay_status " . db_create_in(array(PS_PAYED, PS_PAYING)) . $ext . " GROUP BY g.goods_id HAVING num > $sales_count";
        $res = $GLOBALS['db']->query($sql);

        $rank = $GLOBALS['db']->num_rows($res) + 1;
        if ($rank > 10) $rank = 0; 
    }else{
        $rank = 0;
    }
    return $rank;
}
/* 取得跟商品关联的礼包列表 */
function get_package_goods_list($goods_id){
    $now = gmtime();
    $sql = "SELECT pg.goods_id, ga.act_id, ga.act_name, ga.act_desc, ga.goods_name, ga.start_time, ga.end_time, ga.is_finished, ga.ext_info FROM " . $GLOBALS['ecs']->table('goods_activity') . " AS ga, " . $GLOBALS['ecs']->table('package_goods') . " AS pg WHERE pg.package_id = ga.act_id AND ga.start_time <= '" . $now . "' AND ga.end_time >= '" . $now . "' AND pg.goods_id = '" . $goods_id . "' AND ga.goods_id = '" . $goods_id . "' GROUP BY ga.act_id ORDER BY ga.act_id ";
    $res = $GLOBALS['db']->getAll($sql);

    foreach ($res as $tempkey => $value){
        $subtotal = 0;
        $row = unserialize($value['ext_info']);
        unset($value['ext_info']);
        if ($row){
            foreach ($row as $key=>$val){ $res[$tempkey][$key] = $val; }
        }

        $sql = "SELECT pg.package_id, pg.goods_id, pg.goods_number, pg.admin_id, p.goods_attr, g.goods_sn, g.goods_name, g.market_price, g.goods_thumb, IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS rank_price FROM " . $GLOBALS['ecs']->table('package_goods') . " AS pg LEFT JOIN ". $GLOBALS['ecs']->table('goods') . " AS g ON g.goods_id = pg.goods_id LEFT JOIN ". $GLOBALS['ecs']->table('products') . " AS p ON p.product_id = pg.product_id LEFT JOIN " . $GLOBALS['ecs']->table('member_price') . " AS mp ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' WHERE pg.package_id = " . $value['act_id']. " ORDER BY pg.package_id, pg.goods_id";

        $goods_res = $GLOBALS['db']->getAll($sql);
        foreach($goods_res as $key => $val){
            $goods_id_array[] = $val['goods_id'];
            $goods_res[$key]['goods_thumb']  = get_image_path($val['goods_id'], $val['goods_thumb'], true);
            $goods_res[$key]['market_price'] = price_format($val['market_price']);
            $goods_res[$key]['rank_price']   = price_format($val['rank_price']);
            $subtotal += $val['rank_price'] * $val['goods_number'];
        }

        $sql = "SELECT ga.goods_attr_id, ga.attr_value FROM " .$GLOBALS['ecs']->table('goods_attr'). " AS ga, " .$GLOBALS['ecs']->table('attribute'). " AS a WHERE a.attr_id = ga.attr_id AND a.attr_type = 1 AND " . db_create_in($goods_id_array, 'goods_id');
        $result_goods_attr = $GLOBALS['db']->getAll($sql);

        $_goods_attr = array();
        foreach ($result_goods_attr as $value){ $_goods_attr[$value['goods_attr_id']] = $value['attr_value']; }

        $format = '[%s]';
        foreach($goods_res as $key => $val){
            if ($val['goods_attr'] != ''){
                $goods_attr_array = explode('|', $val['goods_attr']);

                $goods_attr = array();
                foreach ($goods_attr_array as $_attr){ $goods_attr[] = $_goods_attr[$_attr]; }

                $goods_res[$key]['goods_attr_str'] = sprintf($format, implode('，', $goods_attr));
            }
        }

        $res[$tempkey]['goods_list']    = $goods_res;
        $res[$tempkey]['subtotal']      = price_format($subtotal);
        $res[$tempkey]['saving']        = price_format(($subtotal - $res[$tempkey]['package_price']));
        $res[$tempkey]['package_price'] = price_format($res[$tempkey]['package_price']);
    }
    return $res;
}
function get_package_goods_list_120($goods_id){
	$now = gmtime();
    $sql = "SELECT ga.act_id,ga.act_name,ga.ext_info FROM " . $GLOBALS['ecs']->table('goods_activity') . " AS ga, " . $GLOBALS['ecs']->table('package_goods') . " AS pg WHERE pg.package_id = ga.act_id AND ga.start_time <= '" . $now . "' AND ga.end_time >= '" . $now . "' AND pg.goods_id = " . $goods_id . " AND ga.goods_id = " . $goods_id . " GROUP BY pg.package_id ORDER BY ga.act_id";

	$res = $GLOBALS['db']->getAll($sql);

    foreach ($res as $tempkey => $value){
        $subtotal = 0;
		$i=1;

		$row = unserialize($value['ext_info']);
        unset($value['ext_info']);
        if ($row){
            foreach ($row as $key=>$val){ $res[$tempkey][$key] = $val; }
        }

        $sql = "SELECT pg.package_id, pg.goods_id, pg.product_id, pg.goods_number, pg.admin_id, p.goods_attr, g.goods_sn, g.goods_name, g.market_price, g.goods_thumb, IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS rank_price FROM " . $GLOBALS['ecs']->table('package_goods') . " AS pg LEFT JOIN ". $GLOBALS['ecs']->table('goods') . " AS g ON g.goods_id = pg.goods_id LEFT JOIN ". $GLOBALS['ecs']->table('products') . " AS p ON p.product_id = pg.product_id LEFT JOIN " . $GLOBALS['ecs']->table('member_price') . " AS mp ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' WHERE pg.package_id = " . $value['act_id']. " ORDER BY pg.package_id, pg.goods_id";

		$goods_ress = $GLOBALS['db']->query($sql);
		$goods_res = array();
		while ($row = $GLOBALS['db']->fetchRow($goods_ress)){
			if ($row['goods_id'] == $goods_id ){
				$goods_res[0]=$row;
			}else{
				$goods_res[$i]=$row;
				$i++;
			}
		}

        foreach($goods_res as $key => $val){
            $goods_id_array[] = $val['goods_id'];
            $goods_res[$key]['goods_thumb']  = get_image_path($val['goods_id'], $val['goods_thumb'], true);
            $goods_res[$key]['market_price'] = price_format($val['market_price']);
            $goods_res[$key]['rank_price']   = $val['rank_price'];
            $subtotal += $val['rank_price'] * $val['goods_number'];
        }

        /* 取商品属性 */
        $sql = "SELECT ga.goods_attr_id, ga.attr_value FROM " .$GLOBALS['ecs']->table('goods_attr'). " AS ga, " .$GLOBALS['ecs']->table('attribute'). " AS a WHERE a.attr_id = ga.attr_id AND a.attr_type = 1 AND " . db_create_in($goods_id_array, 'goods_id');
        $result_goods_attr = $GLOBALS['db']->getAll($sql);

        $_goods_attr = array();
        foreach ($result_goods_attr as $value){ $_goods_attr[$value['goods_attr_id']] = $value['attr_value']; }

        $format = '[%s]';
        foreach($goods_res as $key => $val){
            if ($val['goods_attr'] != ''){
                $goods_attr_array = explode('|', $val['goods_attr']);

                $goods_attr = array();
                foreach ($goods_attr_array as $_attr){ $goods_attr[] = $_goods_attr[$_attr]; }

                $goods_res[$key]['goods_attr_str'] = sprintf($format, implode('，', $goods_attr));
            }
        }
		ksort($goods_res);
		$zhekou=  round(($res[$tempkey]['package_price'] / $subtotal), 8);
		foreach($goods_res as $key => $val){
			$goods_res[$key]['rank_price_zk']=$val['rank_price'] * $zhekou;
			$goods_res[$key]['rank_price_zk_format']= price_format($goods_res[$key]['rank_price_zk']);
		}
        $res[$tempkey]['goods_list']    = $goods_res;
        $res[$tempkey]['subtotal']      = price_format($subtotal);
		$res[$tempkey]['zhekou']		= $zhekou*100;
        $res[$tempkey]['saving']        = price_format(($subtotal - $res[$tempkey]['package_price']));
        $res[$tempkey]['package_price'] = price_format($res[$tempkey]['package_price']);

    }
	return $res;
}

/* 获得指定品牌的详细信息 */
function get_brand_info($id){
    $sql = 'SELECT * FROM ' . $GLOBALS['ecs']->table('brand') . " WHERE brand_id = '$id'";

    return $GLOBALS['db']->getRow($sql);
}

/* 获得指定品牌下的推荐和促销商品 */
function brand_recommend_goods($type, $brand, $cat = 0){
    static $result = NULL;

    $time = gmtime();

    if ($result === NULL){
        if ($cat > 0){
            $cat_where = "AND " . get_children($cat);
        }else{
            $cat_where = '';
        }

        $sql = "SELECT g.goods_id, g.goods_name, g.market_price, g.shop_price AS org_price, g.promote_price, IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS shop_price, promote_start_date, promote_end_date, g.goods_brief, g.goods_thumb, goods_img, b.brand_name, g.is_best, g.is_new, g.is_hot, g.is_promote FROM " . $GLOBALS['ecs']->table('goods') . ' AS g LEFT JOIN ' . $GLOBALS['ecs']->table('brand') . ' AS b ON b.brand_id = g.brand_id LEFT JOIN ' . $GLOBALS['ecs']->table('member_price') . " AS mp ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' WHERE g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 AND g.brand_id = '$brand' AND (g.is_best = 1 OR (g.is_promote = 1 AND promote_start_date <= '$time' AND promote_end_date >= '$time')) $cat_where ORDER BY g.sort_order, g.last_update DESC";
        $result = $GLOBALS['db']->getAll($sql);
    }

    $num = 0;
    $type2lib = array('best'=>'recommend_best', 'new'=>'recommend_new', 'hot'=>'recommend_hot', 'promote'=>'recommend_promotion');
    $num = get_library_number($type2lib[$type]);

    $idx = 0;
    $goods = array();
    foreach ($result AS $row){
        if ($idx >= $num) break; 

        if (($type == 'best' && $row['is_best'] == 1) || ($type == 'promote' && $row['is_promote'] == 1 && $row['promote_start_date'] <= $time && $row['promote_end_date'] >= $time)){
            if ($row['promote_price'] > 0){
                $promote_price = bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']);
                $goods[$idx]['promote_price'] = $promote_price > 0 ? price_format($promote_price) : '';
            }else{
                $goods[$idx]['promote_price'] = '';
            }

            $goods[$idx]['id']           = $row['goods_id'];
            $goods[$idx]['name']         = $row['goods_name'];
            $goods[$idx]['brief']        = $row['goods_brief'];
            $goods[$idx]['brand_name']   = $row['brand_name'];
            $goods[$idx]['short_style_name']   = $GLOBALS['_CFG']['goods_name_length'] > 0 ? sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name'];
            $goods[$idx]['market_price'] = price_format($row['market_price']);
            $goods[$idx]['shop_price']   = price_format($row['shop_price']);
            $goods[$idx]['thumb']        = get_image_path($row['goods_id'], $row['goods_thumb'], true);
            $goods[$idx]['goods_img']    = get_image_path($row['goods_id'], $row['goods_img']);
            $goods[$idx]['url']          = build_uri('goods', array('gid' => $row['goods_id']), $row['goods_name']);

            $idx++;
        }
    }
    return $goods;
}

/* 获得指定的品牌下的商品总数 */
function goods_count_by_brand($brand_id, $cate = 0){
    $sql = "SELECT COUNT(*) FROM ".$GLOBALS['ecs']->table('goods'). " AS g WHERE brand_id = '$brand_id' AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0";

    if ($cate > 0) $sql .= " AND " . get_children($cate); 

    return $GLOBALS['db']->getOne($sql);
}

/* 获得品牌下的商品 */
function brand_get_goods($brand_id, $cate, $size, $page, $sort, $order){
    $cate_where = ($cate > 0) ? 'AND ' . get_children($cate) : '';

    $sql = "SELECT g.goods_id, g.goods_name, g.market_price, g.shop_price AS org_price, IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS shop_price, g.promote_price, g.promote_start_date, g.promote_end_date, g.goods_brief, g.goods_thumb , g.goods_img FROM " . $GLOBALS['ecs']->table('goods') . " AS g LEFT JOIN " . $GLOBALS['ecs']->table('category') . " AS c ON c.cat_id = g.cat_id LEFT JOIN " . $GLOBALS['ecs']->table('member_price') . " AS mp ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' WHERE g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 AND g.brand_id = '$brand_id' $cate_where ORDER BY c.rg_sort_order asc, $sort $order";

    $res = $GLOBALS['db']->selectLimit($sql, $size, ($page - 1) * $size);

    $arr = array();
    while ($row = $GLOBALS['db']->fetchRow($res)){
        if ($row['promote_price'] > 0){
            $promote_price = bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']);
        }else{
            $promote_price = 0;
        }

        $arr[$row['goods_id']]['goods_id']      = $row['goods_id'];
        if($GLOBALS['display'] == 'grid'){
            $arr[$row['goods_id']]['goods_name'] = $arr[$row['goods_id']]['name']       = $GLOBALS['_CFG']['goods_name_length'] > 0 ? sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name'];
        }else{
            $arr[$row['goods_id']]['goods_name'] = $arr[$row['goods_id']]['name']       = $row['goods_name'];
        }
        $arr[$row['goods_id']]['market_price']  = price_format($row['market_price']);
        $arr[$row['goods_id']]['shop_price']    = price_format($row['shop_price']);
        $arr[$row['goods_id']]['promote_price'] = ($promote_price > 0) ? price_format($promote_price) : '';
        $arr[$row['goods_id']]['goods_brief']   = $row['goods_brief'];
        $arr[$row['goods_id']]['goods_thumb']   = get_image_path($row['goods_id'], $row['goods_thumb'], true);
        $arr[$row['goods_id']]['goods_img']     = get_image_path($row['goods_id'], $row['goods_img']);
        $arr[$row['goods_id']]['url']           = build_uri('goods', array('gid' => $row['goods_id']), $row['goods_name']);
    }
    return $arr;
}

/* 获得与指定品牌相关的分类 */
function brand_related_cat($brand){
    $arr[] = array('cat_id' => 0, 'cat_name' => $GLOBALS['_LANG']['all_category'], 'url' => build_uri('brand', array('bid' => $brand), $GLOBALS['_LANG']['all_category']));

    $sql = "SELECT c.cat_id, c.cat_name, COUNT(g.goods_id) AS goods_count FROM ". $GLOBALS['ecs']->table('category'). " AS c, ". $GLOBALS['ecs']->table('goods') . " AS g WHERE g.brand_id = '$brand' AND c.cat_id = g.cat_id GROUP BY g.cat_id";
    $res = $GLOBALS['db']->query($sql);

    while ($row = $GLOBALS['db']->fetchRow($res)){
        $row['url'] = build_uri('brand', array('cid' => $row['cat_id'], 'bid' => $brand), $row['cat_name']);
        $arr[] = $row;
    }
    return $arr;
}

function get_article_info($article_id){
    $sql = "SELECT a.*, IFNULL(AVG(r.comment_rank), 0) AS comment_rank FROM " .$GLOBALS['ecs']->table('article'). " AS a LEFT JOIN " .$GLOBALS['ecs']->table('comment'). " AS r ON r.id_value = a.article_id AND comment_type = 1 WHERE a.is_open = 1 AND a.article_id = '$article_id' GROUP BY a.article_id";
    $row = $GLOBALS['db']->getRow($sql);

    if ($row !== false){
        $row['comment_rank'] = ceil($row['comment_rank']);                              // 用户评论级别取整
        $row['add_time']     = local_date($GLOBALS['_CFG']['date_format'], $row['add_time']); // 修正添加时间显示

        if (empty($row['author']) || $row['author'] == '_SHOPHELP'){
            $row['author'] = $GLOBALS['_CFG']['shop_name'];
        }
    }

    return $row;
}
/** 获得文章关联的商品 */
function article_related_goods($id){
    $sql = "SELECT g.goods_id, g.goods_name, g.goods_thumb, g.goods_img, g.shop_price AS org_price, IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS shop_price, g.market_price, g.promote_price, g.promote_start_date, g.promote_end_date FROM " . $GLOBALS['ecs']->table('goods_article') . ' ga LEFT JOIN ' . $GLOBALS['ecs']->table('goods') . ' AS g ON g.goods_id = ga.goods_id LEFT JOIN ' . $GLOBALS['ecs']->table('member_price') . " AS mp ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' WHERE ga.article_id = '$id' AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0";
    $res = $GLOBALS['db']->query($sql);

    $arr = array();
    while ($row = $GLOBALS['db']->fetchRow($res)){
        $arr[$row['goods_id']]['goods_id']      = $row['goods_id'];
        $arr[$row['goods_id']]['goods_name']    = $row['goods_name'];
        $arr[$row['goods_id']]['short_name']	= $GLOBALS['_CFG']['goods_name_length'] > 0 ? sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name'];
        $arr[$row['goods_id']]['goods_thumb']   = get_image_path($row['goods_id'], $row['goods_thumb'], true);
        $arr[$row['goods_id']]['goods_img']     = get_image_path($row['goods_id'], $row['goods_img']);
        $arr[$row['goods_id']]['market_price']  = price_format($row['market_price']);
        $arr[$row['goods_id']]['shop_price']    = price_format($row['shop_price']);
        $arr[$row['goods_id']]['url']           = build_uri('goods', array('gid' => $row['goods_id']), $row['goods_name']);

        if ($row['promote_price'] > 0){
            $arr[$row['goods_id']]['promote_price'] = bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']);
            $arr[$row['goods_id']]['formated_promote_price'] = price_format($arr[$row['goods_id']]['promote_price']);
        }else{
            $arr[$row['goods_id']]['promote_price'] = 0;
        }
    }
    return $arr;
}
?>